package com.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test {
	
	
	public static void main(String[] args) throws Exception {
		new Test().dd();
	}
	
	public void dd() {
		//INSERT INTO `ljxd`.`test`(`index_A`, `index_B`, `index_C`, `field_D`, `name`, `age`, `desc`) 
		//VALUES ('1', '1', '1', 'a', '1001', '小明', '1', '好人一个', '懒得写')
		String sql = "INSERT INTO test(`index_A`, `index_B`, `index_C`, `field_D`, `name`, `age`, `desc`) VALUES (?,?,?,?,?,?,?)";
		Connection conn = null;				//和数据库取得连接
		PreparedStatement pstmt = null;		//创建statement
		try{
			conn = getConnection();
			for (int i = 100513; i < 10000000; i++) {
				pstmt = (PreparedStatement) conn.prepareStatement(sql);
				pstmt.setString(1, "a"+i); //index_A
				pstmt.setString(2, "b"+i); //index_B
				pstmt.setString(3, "c"+i); //index_C
				pstmt.setString(4, "d"+i); //field_D
				pstmt.setString(5, "小明"+i); //name
				pstmt.setString(6, String.valueOf(i+1)); //age
				pstmt.setString(7, "说明说明说明"+i); //desc
				pstmt.executeUpdate();	//执行
				System.out.println("执行等到"+i);
			}
			System.out.println("执行完毕。。。");
		}catch(SQLException e){
			e.printStackTrace();
		}
		finally{
			close(pstmt);
			close(conn);		//必须关闭
		}
	}
	public static Connection getConnection(){
		Connection conn = null;
		 try {
			 	//初始化驱动类com.mysql.jdbc.Driver
	            Class.forName("com.mysql.cj.jdbc.Driver");
	            conn = DriverManager.getConnection("jdbc:mysql://120.77.38.34:13306/test?characterEncoding=UTF-8", "root", "Mysql8@2021");
	        } catch (ClassNotFoundException e) { 				
	            e.printStackTrace();
	        }catch (SQLException e) {							
	            e.printStackTrace();
	        }
		 return conn;
	}
	
	/**
	 * 封装三个关闭方法
	 * @param pstmt
	 */
	public static void close(PreparedStatement pstmt){
		if(pstmt != null){						//避免出现空指针异常
			try{
				pstmt.close();
			}catch(SQLException e){
				e.printStackTrace();
			}
			
		}
	}
	
	public static void close(Connection conn){
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void close(ResultSet rs){
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
